import { Ref, onActivated, onBeforeMount, reactive, ref } from 'vue'
import { exportXLSX } from '/@/utils/exportXLSX'
import { useRouter } from 'vue-router'
import { message } from 'ant-design-vue'

interface Option {
  api: {
    get: (data?: any) => Promise<any>
    delete?: (id: string, data?: any) => Promise<any>
    excel?: (data?: any) => Promise<any>
  } // 接口
  formData?: any // 列表数据
  routerUrl?: string // 路由地址
  isDataExistItems?: boolean // 是否存在items, 用来判断接口返回数据为 数组还是有items和totalCount的对象
  tableOption?: any[] // 表格配置
  getInterceptor?: (treeData: any[]) => void // 列表获取数据回调
  isActivatedGetData?: boolean // 是否在组件挂载时获取列表数据
  isBeforeMountGetData?: boolean // 是否在组件加载完时获取列表数据
}

type TableDataType = {
  _tableList: Ref<any[]> // 列表数据
  _currentPage: Ref<number> // 当前页数
  _pageTotal: Ref<number> // 总页数
  _formData: Ref<any> // 查询条件
  _tableOption: Ref<any[]> // 表格配置
  _getTableList: () => Promise<void> // 获取列表数据
  _onSearch: () => void // 查询
  _tableUpth: (val: any) => void // 更新表格配置
}
type TableHandleType = {
  _onToCreateFn: (query?: any) => void // 跳转新增
  _onToUpdateFn: (id: string, query?: any) => void // 跳转编辑
  _onToDeleteFn: (id: string, query?: any) => void // 删除
  _onToDetailFn: (id: string, query?: any) => void // 跳转详情
  _exportExcalFn: (name: string) => Promise<void> // 导出
}

type TableListResult = [TableDataType, TableHandleType]

const defaultOption = {
  api: {},
  formData: {},
  tableOption: [],
  isDataExistItems: true,
  isActivatedGetData: true,
  isBeforeMountGetData: false,
  routerUrl: ''
}

export function useGetTableList(option?: Option): TableListResult {
  const {
    api,
    formData,
    isDataExistItems,
    tableOption,
    getInterceptor,
    routerUrl,
    isActivatedGetData,
    isBeforeMountGetData
  } = Object.assign(defaultOption, option)

  const router = useRouter()

  const _currentPage = ref(1)
  const _pageTotal = ref(0)
  const _formData = reactive(formData)
  const _tableList = ref([])

  const _tableOption = ref(tableOption)
  const _tableUpth = (val: any) => (_tableOption.value = val)

  // 获取列表数据
  const _getTableList = async () => {
    const result = await api.get(_formData)
    if (isDataExistItems) {
      getInterceptor && getInterceptor(result.items)
      _tableList.value = result.items
      _pageTotal.value = result.totalCount
    } else {
      getInterceptor && getInterceptor(result)
      _tableList.value = result
    }
  }

  const _onSearch = () => {
    // 重置分页
    if (_formData.skipCount) _formData.skipCount = 0
    _currentPage.value = 1
    _getTableList()
  }

  // 列表操作函数
  const _exportExcalFn = async (name: string) => {
    if (!api.excel) return
    try {
      const result = await api.excel(_formData)
      exportXLSX(
        result.data,
        { header: result.headers },
        {
          fileName: name
        }
      )
    } catch {}
  }
  const _onToUpdateFn = (id: string, query?: any) => {
    router.push({ path: `${routerUrl}/update/${id}`, query })
  }
  const _onToCreateFn = (query?: any) => {
    router.push({ path: `${routerUrl}/add`, query })
  }
  const _onToDetailFn = (id: string, query?: any) => {
    router.push({ path: `${routerUrl}/detail/${id}`, query })
  }
  const _onToDeleteFn = async (id: string) => {
    if (!api.delete) return
    try {
      await api.delete(id)
      await _getTableList()
      message.success('删除成功')
    } catch {
      message.error('删除失败')
    }
  }
  // 在组件挂载时获取列表数据
  onActivated(() => {
    isActivatedGetData && _getTableList()
  })
  onBeforeMount(() => {
    isBeforeMountGetData && _getTableList()
  })

  return [
    {
      _tableList,
      _currentPage,
      _pageTotal,
      _formData,
      _tableOption,
      _getTableList,
      _onSearch,
      _tableUpth
    },
    {
      _onToCreateFn,
      _onToUpdateFn,
      _exportExcalFn,
      _onToDeleteFn,
      _onToDetailFn
    }
  ]
}
